<script setup>
import { ref, onMounted, computed } from 'vue'
import { onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'
import { recommendMerchantAPI } from '@/api/discover'
import MerchantItem from '@/components/MerchantItem.vue'

// 店铺列表数据
const shopList = ref([])
const loading = ref(false)
const finished = ref(false)
const currentPage = ref(1)
const pageSize = 5

// 计算统计数据
const merchantStats = computed(() => {
  if (shopList.value.length === 0) {
    return {
      totalCount: 0,
      averageRating: 0,
      totalRatings: 0
    }
  }

  const total = shopList.value.length
  const totalRatingSum = shopList.value.reduce((sum, shop) => sum + (shop.merchantRating || 0), 0)
  const averageRating = (totalRatingSum / total).toFixed(1)

  const totalRatingCount = shopList.value.reduce((sum, shop) => sum + (shop.ratingCount || 0), 0)
  const formattedRatingCount = totalRatingCount > 10 ? `${Math.floor(totalRatingCount / 10) * 10}+` : totalRatingCount

  return {
    totalCount: total,
    averageRating: parseFloat(averageRating),
    totalRatings: formattedRatingCount
  }
})


// 加载店铺数据
const loadShops = async (isRefresh = false) => {
  if (loading.value || finished.value) return

  loading.value = true
  
  try {
    const page = isRefresh ? 1 : currentPage.value
    const res = await recommendMerchantAPI(page, pageSize)
    
    if (res && res.data) {
      const newShops = res.data.records || []
      
      if (isRefresh) {
        // 刷新时替换数据
        shopList.value = newShops
      } else {
        // 加载更多时追加数据
        shopList.value.push(...newShops)
      }
      
      // 检查是否已经没有更多数据
      if (newShops.length < pageSize) {
        finished.value = true
      } else {
        currentPage.value++
      }
    } else {
      if (!isRefresh && shopList.value.length === 0) {
        uni.showToast({
          title: '暂无店铺数据',
          icon: 'none'
        })
      }
      finished.value = true
    }
  } catch (error) {
    console.error('加载店铺失败:', error)
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none'
    })
    if (shopList.value.length === 0) {
      finished.value = true
    }
  } finally {
    loading.value = false
  }
}

// 下拉刷新处理
const handleRefresh = async () => {
  currentPage.value = 1
  finished.value = false
  await loadShops(true)
  // 结束下拉刷新动画
  uni.stopPullDownRefresh()
}

// 页面加载时初始化数据
onMounted(() => {
  loadShops(true)
})

// 监听上拉触底事件
onReachBottom(() => {
  if (!finished.value && !loading.value) {
    loadShops(false)
  }
})

// 监听下拉刷新事件 - 关键实现
onPullDownRefresh(() => {
  handleRefresh()
})
</script>

<template>
  <view class="discover-container">
    <!-- 店铺区域标题 -->
    <view class="shop-section-title discover-card">
      <view class="title-header">
        <text class="title-text">
          <text class="iconfont icon-shop"></text>
          发现店铺
        </text>
        <view class="title-badge">
          <text class="iconfont icon-jingxuan"></text>
          精选
        </view>
      </view>
      <text class="title-subtitle">为你推荐优质店铺</text>
      <view class="stats-row">
        <view class="stat-item">
          <text class="stat-number">{{ merchantStats.totalCount }}</text>
          <text class="stat-label">已推荐</text>
        </view>
        <view class="stat-divider"></view>
        <view class="stat-item">
          <text class="stat-number">{{ merchantStats.totalRatings }}</text>
          <text class="stat-label">用户评分</text>
        </view>
        <view class="stat-divider"></view>
        <view class="stat-item">
          <text class="stat-number">{{ merchantStats.averageRating }}</text>
          <text class="stat-label">平均评分</text>
        </view>
      </view>
    </view>

    <!-- 无限加载店铺列表 -->
    <view class="shop-list-container">
      <view
        v-for="(merchant, index) in shopList"
        :key="merchant.id"
        class="shop-item-wrapper"
        :style="{ animationDelay: `${index * 0.1}s` }"
      >
        <MerchantItem :merchant="merchant" />
      </view>

      <!-- 加载状态 -->
      <view v-if="loading && !finished" class="loading-container">
        <view class="loading-spinner"></view>
        <text>发现更多店铺中...</text>
      </view>

      <!-- 加载完成提示 -->
      <view v-if="finished && !loading" class="finished-container">
        <text>🏪 已经没有更多店铺了~</text>
      </view>

      <!-- 下拉加载提示 -->
      <view
        v-if="!finished && !loading && shopList.length > 0"
        class="scroll-tip-container"
      >
        <text>👇 下拉发现更多店铺</text>
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.discover-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 40rpx 0 calc(20rpx + env(safe-area-inset-bottom)) 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.discover-card {
  max-width: 600rpx;
  margin: 0 auto 48rpx auto;
  width: 100%;
}

// 店铺区域标题
.shop-section-title {
  width: 100%;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 40rpx;
  padding: 48rpx 40rpx;
  margin: 0 0 48rpx 0;
  box-shadow: 0 16rpx 64rpx rgba(0, 0, 0, 0.1);
  border: 2rpx solid rgba(255, 255, 255, 0.2);
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 6rpx;
    background: linear-gradient(90deg, #667eea, #764ba2, #f093fb, #f5576c);
    background-size: 200% 100%;
    animation: gradientShift 3s ease-in-out infinite;
  }

  .title-header {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 24rpx;
    margin-bottom: 16rpx;

    .title-text {
      font-size: 40rpx;
      font-weight: 600;
      color: #333;
      margin: 0;
      display: flex;
      align-items: center;

      .iconfont {
        font-size: 44rpx;
        color: #667eea;
        margin-right: 16rpx;
      }
    }

    .title-badge {
      background: linear-gradient(45deg, #ff6b6b, #ff8e8e);
      color: white;
      padding: 8rpx 24rpx;
      border-radius: 24rpx;
      font-size: 24rpx;
      font-weight: 600;
      display: flex;
      align-items: center;
      gap: 8rpx;
      box-shadow: 0 4rpx 16rpx rgba(255, 107, 107, 0.3);

      .iconfont {
        font-size: 24rpx;
      }
    }
  }

  .title-subtitle {
    font-size: 28rpx;
    color: #999;
    margin: 0 0 32rpx 0;
    opacity: 0.8;
    text-align: center;
    display: block;
  }

  .stats-row {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 32rpx;

    .stat-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 8rpx;

      .stat-number {
        font-size: 36rpx;
        font-weight: 700;
        color: #667eea;
        line-height: 1;
      }

      .stat-label {
        font-size: 22rpx;
        color: #999;
        opacity: 0.8;
      }
    }

    .stat-divider {
      width: 2rpx;
      height: 48rpx;
      background: linear-gradient(
        to bottom,
        transparent,
        rgba(102, 126, 234, 0.3),
        transparent
      );
    }
  }
}

// 店铺列表容器
.shop-list-container {
  width: 100%;
  max-width: 600rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 32rpx;
  margin: 0 auto;
  padding: 0 0 40rpx 0;
}

.shop-item-wrapper {
  width: 100%;
  margin-bottom: 32rpx;
  animation: fadeInUp 0.6s ease forwards;
  opacity: 0; // 初始隐藏，通过动画显示
}

.shop-item-wrapper:last-child {
  margin-bottom: 0;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 40rpx;
  color: #666;
}

.loading-spinner {
  width: 64rpx;
  height: 64rpx;
  border: 6rpx solid rgba(102, 126, 234, 0.2);
  border-top: 6rpx solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 32rpx;
}

.finished-container {
  text-align: center;
  padding: 80rpx 40rpx;
  color: #999;
}

.scroll-tip-container {
  text-align: center;
  padding: 60rpx 40rpx;
  color: #999;
}

.scroll-tip-container text {
  font-size: 26rpx;
  margin: 0;
  opacity: 0.6;
  animation: bounce 2s infinite;
}

// 动画
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(60rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

@keyframes bounce {
  0%,
  20%,
  50%,
  80%,
  100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-20rpx);
  }
  60% {
    transform: translateY(-10rpx);
  }
}

@keyframes gradientShift {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}
</style>
